package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Category;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
    private CatalogService catalogService;
    private static final String CATEGORY_FORM = "/WEB-INF/jsp/catalog/category.jsp";


    private static final String PRODUCT_FORM = "/WEB-INF/jsp/catalog/product.jsp";


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {



    }
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String categoryId = req.getParameter("keyword");
        boolean containsDigit = containsDigitUsingLoop(categoryId);


        if(!containsDigit)
        {
            catalogService = new CatalogService();
            Category category = catalogService.getCategory(categoryId);
            List<Product> productList = catalogService.getProductListByCategory(categoryId);


            HttpSession session = req.getSession();
            session.setAttribute("category",category);
            session.setAttribute("productList",productList);
            req.getRequestDispatcher(CATEGORY_FORM).forward(req,resp);
        }
        else
        {
            String productId = categoryId;
            catalogService = new CatalogService();
            Product product = catalogService.getProduct(productId);
            List<Item> itemList = catalogService.getItemListByProduct(productId);

            HttpSession session = req.getSession();
            session.setAttribute("product",product);
            session.setAttribute("itemList",itemList);
            req.getRequestDispatcher(PRODUCT_FORM).forward(req,resp);
        }



    }
    private static boolean containsDigitUsingLoop(String str) {
        for (char c : str.toCharArray()) {
            if (Character.isDigit(c)) {
                return true;
            }
        }
        return false;
    }
}



